package com.ideabove.radio.module;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.protocol.HTTP;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.facebook.Session;
import com.facebook.android.AsyncFacebookRunner;
import com.facebook.android.BaseRequestListener;
import com.facebook.android.Facebook;
import com.facebook.android.Utility;
import com.ideabove.adapter.CommentAdapter;
import com.ideabove.adapter.FolderAdapter;
import com.ideabove.adapter.FolderEditAdapter;
import com.ideabove.data.Comment;
import com.ideabove.data.Folder;
import com.ideabove.data.PlayItem;
import com.ideabove.network.NetWorkManager;
import com.ideabove.radio.MainActivity;
import com.ideabove.radio.R;
import com.ideabove.radio.module.FacebookMd.UserRequestListener;
import com.ideabove.util.ConnectThread;
import com.ideabove.util.img.ImageLoader;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.graphics.PorterDuff.Mode;
import android.graphics.Typeface;
import android.net.Uri;
import android.os.Bundle;
import android.os.Message;
import android.os.RemoteException;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.ScaleXSpan;
import android.text.style.StyleSpan;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;

public class SongInsertMd extends ModuleAbs{

	PlayItem mCurPlayItem;
	
	public void init(MainActivity activity){
		super.init(activity);		
	}
	
	interface ShowSongInsertCallback{
		public void callback();
	}

	
	// 폴더명을 가져온다.
	public String getFolderTitle(String folderId, ArrayList<Folder> folderList){		
		String folderTitle = null;
		if(!TextUtils.isEmpty(folderId)){
			for(int i = 0; i < folderList.size(); i++){
				String listFolderId = folderList.get(i).getFolder_id();
				
				if(folderId.equals(listFolderId)){
					folderTitle = folderList.get(i).getTitle();
					break;
				}				
			}
		}		
		return folderTitle;
	}
	
	// 모든 장르 채크 해제
	public void unCheckAllGenre(){
		LinearLayout inGenresLayout = (LinearLayout)activity.findViewById(R.id.user_interest_genres);
		
		for(int k = 0; k < inGenresLayout.getChildCount(); k++){
			LinearLayout root = (LinearLayout)inGenresLayout.getChildAt(k);
			
			for(int i = 0; i < root.getChildCount(); i++){
				FrameLayout fLayout = (FrameLayout)root.getChildAt(i);
				ImageView tcheck = (ImageView)((FrameLayout)fLayout).getChildAt(1);
				tcheck.setVisibility(View.GONE);
			}								
		}
	}
	
	// 채크된 장르 아이디 가져오기
	public String getGenreId(){
		String genreId = null;
		LinearLayout inGenresLayout = (LinearLayout)activity.findViewById(R.id.user_interest_genres);
		
		for(int k = 0; k < inGenresLayout.getChildCount(); k++){
			LinearLayout root = (LinearLayout)inGenresLayout.getChildAt(k);
			
			for(int i = 0; i < root.getChildCount(); i++){
				FrameLayout fLayout = (FrameLayout)root.getChildAt(i);
				ImageView tcheck = (ImageView)((FrameLayout)fLayout).getChildAt(1);
				if(tcheck.getVisibility() == View.VISIBLE){
					genreId = (String)fLayout.getContentDescription();
					break;
				}
			}								
		}
		return genreId;
	}
	


	// 곡등록
	public synchronized void requestInsertNewSongInfo(final PlayItem playItem){
		int timeout = 3;
		new ConnectThread(timeout).setCallback(new ConnectThread.Callback() {
			
			@Override
			public void fail(Object result) {
				// TODO Auto-generated method stub
				AlertDialog.Builder ab=new AlertDialog.Builder(activity); 
				ab.setMessage("네트워크가 원활하지 않습니다.\n다시 시도해주세요.");					
				ab.setPositiveButton("ok", null);  
				ab.show();
			}
			
			@Override
			public void sucess(Object result){
				if(activity.folderDetailMd.currentFolder == null){
					activity.folderMd.showFolderList();
				}else{
					String fId = playItem.getFolderId();
					Folder folderToShow = activity.folderMd.getFolderById(fId);
					
					if(folderToShow != null){
						activity.folderDetailMd.showFolderDetail(folderToShow, null);
					}else{
						activity.folderMd.showFolderList();
					}					
				}
				
			}
			
			@Override
			public void threadProcess(ConnectThread resultset) throws Exception {
				
				// TODO Auto-generated method stub					
				HttpClient client = NetWorkManager.getHttpConnection();    
				HttpConnectionParams.setConnectionTimeout(client.getParams(), 1000);					

				HttpPost post = new HttpPost("http://14.63.217.155/radio_bonosound/addSong.php");

//				2.	parameter 
//				1.	uId : 유저ID 
//				2.	link : 유투브 링크 
//				3.	title : 유투브 제목 
//				4.	author : 유투브 포스트 올린이 
//				5.	post : 유저가 작성한 내용 
//				6.	viewCnt : 유투브 포스트 뷰 카운트 
//				7.	duration : 포스트 재생시간(초) 
//				8.	fId:선택된폴더ID 
//				9.	gId:선택된장르ID 
 
				
				String uId = activity.facebookMd.getBonoUserId();
				String link = playItem.getLink();
				String title = playItem.getTitle();
				String author = playItem.getAuthor();
				String ytpost = playItem.getPost();
				String viewCnt = playItem.getViewCnt();
				String duration = playItem.getDuration();
				String fId = playItem.getFolderId();
				String gId = playItem.getGenre_id();				
				
				if(TextUtils.isEmpty(uId) 
						&& TextUtils.isEmpty(link)
						&& TextUtils.isEmpty(title)
						&& TextUtils.isEmpty(author)
						&& TextUtils.isEmpty(ytpost) 
						&& TextUtils.isEmpty(viewCnt)
						&& TextUtils.isEmpty(duration)
						&& TextUtils.isEmpty(fId)
						&& TextUtils.isEmpty(gId)
						){
					throw new Exception("parameter error");
				}				
				
				List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
				params.add(new BasicNameValuePair("uId", uId));
				params.add(new BasicNameValuePair("link", link));
				params.add(new BasicNameValuePair("title", title));
				params.add(new BasicNameValuePair("author", author));
				params.add(new BasicNameValuePair("post", ytpost));
				params.add(new BasicNameValuePair("viewCnt", viewCnt));
				params.add(new BasicNameValuePair("duration", duration));
				params.add(new BasicNameValuePair("fId", fId));
				params.add(new BasicNameValuePair("gId", gId));
				
//				Log.e("#########request", "########" + post.getURI().toURL());
//				Log.e("#########request", "########" + params);
				
				UrlEncodedFormEntity ent = new UrlEncodedFormEntity(params,HTTP.UTF_8);
				post.setEntity(ent);
				HttpResponse responsePOST = client.execute(post);  

				InputStream in = responsePOST.getEntity().getContent();
				BufferedReader reader = new BufferedReader(new InputStreamReader(in));
				StringBuilder str = new StringBuilder();
				String line = null;
				while((line = reader.readLine()) != null)
				{					
					str.append(line);
				}
				in.close();					
				String jsonStr = str.toString();
//				Log.e("#########result", "########" + jsonStr);
				
				
			}
		}).start(); 
	}
	
	public boolean checkData(PlayItem playItem){
		if(TextUtils.isEmpty(playItem.getFolderId()) ){
			AlertDialog.Builder ab=new AlertDialog.Builder(activity); 
			ab.setMessage("폴더를 선택 해주세요");					
			ab.setPositiveButton("ok", null);  
			ab.show();
		}else if(TextUtils.isEmpty(playItem.getGenre_id()) ){
			AlertDialog.Builder ab=new AlertDialog.Builder(activity); 
			ab.setMessage("장르를 선택해 주세요");					
			ab.setPositiveButton("ok", null);  
			ab.show();			
		}else {
			
			return true;
		}
		return false;
	}
	

	public void showSongInsert(final PlayItem pitem, final ShowSongInsertCallback callback){
		ModuleAbs.showProgressDialog(activity, "", "잠시만 기다려주세요...");
		this.mCurPlayItem = pitem; 
		
		// 엑티비티에 뷰를 세팅한다.		
		activity.setCurrentMoudle(this);
		View view = (View)activity.findViewById(R.id.flipper_layout);
		view.setVisibility(View.VISIBLE);

		LinearLayout studioMain = (LinearLayout)activity.findViewById(R.id.studio_main);		

		LayoutInflater layoutInflater = (LayoutInflater) 
		activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		View viewToInsert = (View)layoutInflater.inflate(R.layout.studio_song_insert, null);	
		studioMain.removeAllViews();
		studioMain.addView(viewToInsert); 

		int timeout = 3;
		new ConnectThread(timeout).setCallback(new ConnectThread.Callback() {

			@Override
			public void fail(Object result) {
				// TODO Auto-generated method stub
				ModuleAbs.hideProgressDialog();
				AlertDialog.Builder ab=new AlertDialog.Builder(activity); 
				ab.setMessage("네트워크가 원활하지 않습니다.\n다시 시도해주세요.");					
				ab.setPositiveButton("ok", null);  
				ab.show();
			}

			@Override
			public void sucess(Object result){
				ModuleAbs.hideProgressDialog();
				
				final ArrayList<Folder> folderArr = (ArrayList<Folder>)result;
				final String[] folderNameArr = new String[folderArr.size()];
				for(int i = 0; i < folderArr.size(); i++){
					folderNameArr[i] = folderArr.get(i).getTitle();
				}								
				
				// 곡 사진
				ImageView imgView = (ImageView)activity.findViewById(R.id.user_song_pic);
				ImageLoader.download(pitem.getThumbUrl(), imgView);
				
				// 곡 제목
				TextView user_song_title = (TextView)activity.findViewById(R.id.user_song_title);
				user_song_title.setText(pitem.getTitle());
				
				// 뷰카운트
				TextView user_song_view_cnt = (TextView)activity.findViewById(R.id.user_song_view_cnt);
				user_song_view_cnt.setText("Veiw  " + pitem.getViewCnt());
				
				// 장르선택 텍스트 바
				TextView genre_choice_title_bar_text = (TextView)activity.findViewById(R.id.genre_choice_title_bar_text);
				genre_choice_title_bar_text.setText("장르를 선택해 주세요(해당 장르 클릭)");
				
				// 곡내용
				TextView song_content = (TextView)activity.findViewById(R.id.song_content);
				song_content.setText(pitem.getPost());
				
				
				// 폴더선택 버튼
				final TextView song_folder_choosed_text = (TextView)activity.findViewById(R.id.song_folder_choosed_text);				
				
				ImageView song_folder_choice = (ImageView) activity.findViewById(R.id.song_folder_choice);
				
				// 채크박스 다이얼 로그 
				AlertDialog.Builder builder = new AlertDialog.Builder(activity);												
				builder.setTitle("폴더 선택");				
				builder.setSingleChoiceItems(folderNameArr, -1, new DialogInterface.OnClickListener() {
				    public void onClick(DialogInterface dialog, int item) {
				    	song_folder_choosed_text.setText(folderNameArr[item]);
				    	song_folder_choosed_text.setTag(folderArr.get(item).getFolder_id());
				    	dialog.cancel();
				    }
				});
				
				final AlertDialog alert = builder.create();		
				
				// 폴더 선택 버튼
				song_folder_choice.setOnTouchListener(new View.OnTouchListener() {				
					@Override
					public boolean onTouch(View v, MotionEvent event) {
						// TODO Auto-generated method stub
						
						ImageView view = (ImageView)v;
						if(event.getAction() == MotionEvent.ACTION_DOWN){
							view.setPadding(2, 2, 2, 2);
							view.setColorFilter(0xaa111111,Mode.SRC_OVER);			
							
						}else if(event.getAction() == MotionEvent.ACTION_UP){				
							
							if(!alert.isShowing()){
								alert.show();
							}							
							
							view.setPadding(0, 0, 0, 0);
							view.setColorFilter(0x00000000, Mode.SRC_OVER);				
						}
												
						return true;
					}
				});
				
				
				// 장르 선택 하기				
				LinearLayout inGenresLayout = (LinearLayout)activity.findViewById(R.id.user_interest_genres);
				
				
				for(int k = 0; k < inGenresLayout.getChildCount(); k++){
					LinearLayout root = (LinearLayout)inGenresLayout.getChildAt(k);
					
					for(int i = 0; i < root.getChildCount(); i++){						
						FrameLayout fLayout = (FrameLayout)root.getChildAt(i);		
						final ImageView genreImg = (ImageView)((FrameLayout)fLayout).getChildAt(0);
						final ImageView tcheck = (ImageView)((FrameLayout)fLayout).getChildAt(1);
						
						
						fLayout.setOnTouchListener(new OnTouchListener() {
							
							@Override
							public boolean onTouch(View v, MotionEvent event) {
								// TODO Auto-generated method stub
								if(event.getAction() == MotionEvent.ACTION_DOWN){
									genreImg.setPadding(2, 2, 2, 2);
									genreImg.setColorFilter(0xaa111111,Mode.SRC_OVER);			
									
								}else if(event.getAction() == MotionEvent.ACTION_UP){				
									
									
									// 모든 채크된 장르를 지운다..
									unCheckAllGenre();
									
									// 그다음 채크 한다.
									tcheck.setVisibility(View.VISIBLE);
									genreImg.setPadding(0, 0, 0, 0);
									genreImg.setColorFilter(0x00000000, Mode.SRC_OVER);				
								}else{
									genreImg.setPadding(0, 0, 0, 0);
									genreImg.setColorFilter(0x00000000, Mode.SRC_OVER);
								}
								return true;
							}
						});
					}								
				}
				
				// 설정 저장(오른쪽 상단 버튼)
				View btn_top_right_btn_wrap = (View)activity.findViewById(R.id.btn_top_right_btn_wrap);
				btn_top_right_btn_wrap.setVisibility(View.VISIBLE);
				TextView btn_top_right_text = (TextView)activity.findViewById(R.id.btn_top_right_text);
				btn_top_right_text.setText("Save");				
				ImageView btn_top_right_img = (ImageView)activity.findViewById(R.id.btn_top_right_img);
				btn_top_right_img.setOnTouchListener(new View.OnTouchListener() {
					
					@Override
					public boolean onTouch(View v, MotionEvent event) {
						// TODO Auto-generated method stub
						ImageView view = (ImageView)v;
						if(event.getAction() == MotionEvent.ACTION_DOWN){
							view.setPadding(2, 2, 2, 2);
							view.setColorFilter(0xaa111111,Mode.SRC_OVER);				
						}else if(event.getAction() == MotionEvent.ACTION_UP){
																							
							// 장르아이디
							pitem.setGenre_id(getGenreId());
							
							// 곡 포스트
							TextView song_content = (TextView)activity.findViewById(R.id.song_content);														
							pitem.setPost(song_content.getText().toString());
							
							// 폴더아이디
							if(song_folder_choosed_text.getTag() == null){
								pitem.setFolderId(null);
							}else{
								pitem.setFolderId(song_folder_choosed_text.getTag().toString());
							}
							
							if(checkData(pitem)){
								requestInsertNewSongInfo(pitem);
							}							
							
							view.setPadding(0, 0, 0, 0);
							view.setColorFilter(0x00000000, Mode.SRC_OVER);
						}else{
							view.setPadding(0, 0, 0, 0);
							view.setColorFilter(0x00000000, Mode.SRC_OVER);
						}
						return true;
					}
				});
				
			}

			@Override
			public void threadProcess(ConnectThread resultSet) throws Exception {
				
				
				// 폴더리스트를 가져온다.
				HttpClient client = NetWorkManager.getHttpConnection();    
				HttpConnectionParams.setConnectionTimeout(client.getParams(), 1000);					

				HttpPost post = new HttpPost("http://14.63.217.155/radio_bonosound/folderList.php");

				String userId = activity.facebookMd.getBonoUserId();				
				if(TextUtils.isEmpty(userId)){
					throw new Exception("parameter error");
				}

				List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
				params.add(new BasicNameValuePair("uId", userId));

				UrlEncodedFormEntity ent = new UrlEncodedFormEntity(params,HTTP.UTF_8);
				post.setEntity(ent);
				HttpResponse responsePOST = client.execute(post);

				InputStream in = responsePOST.getEntity().getContent();
				BufferedReader reader = new BufferedReader(new InputStreamReader(in));
				StringBuilder str = new StringBuilder();
				String line = null;
				while((line = reader.readLine()) != null)
				{					
					str.append(line);
				}
				in.close();					
				String jsonStr = str.toString();

//				Log.e("#########", "#########" + jsonStr);
				ArrayList<Folder> folderArr = new ArrayList<Folder>();
				
				if(jsonStr != null && jsonStr.length() > 0){					
					
//					결과					
//			        a. folder_id : 폴더 ID
//			        b. folder_name : 폴더명 

					
					try{			
						JSONObject jsonObj = new JSONObject(jsonStr); 
						JSONArray resultArray = jsonObj.getJSONArray("result");

						for (int i = 0; i < resultArray.length(); i++) {
							Folder folder = new Folder();
							
							folder.setFolder_id(resultArray.getJSONObject(i).getString("folder_id").toString());
							folder.setTitle(resultArray.getJSONObject(i).getString("folder_name").toString());
							folderArr.add(folder);
						}
					}catch(Exception e){
						e.printStackTrace();
					}
				}	
					
				resultSet.setResult(folderArr);
			}
		}
		).start(); 
	}
	
	@Override
	public void showMd(){
		View btn_top_right_btn_wrap = (View)activity.findViewById(R.id.btn_top_right_btn_wrap);
		btn_top_right_btn_wrap.setVisibility(View.VISIBLE);
		
		View btn_top_left_btn_wrap = (View)activity.findViewById(R.id.btn_top_left_btn_wrap);
		btn_top_left_btn_wrap.setVisibility(View.GONE);
	}

	@Override
	public void backMd(){
		
		if(activity.folderDetailMd.currentFolder == null){
			activity.folderMd.showFolderList();
		}else{
			String fId = mCurPlayItem.getFolderId();
			Folder folderToShow = activity.folderMd.getFolderById(fId);
			
			if(folderToShow != null){
				activity.folderDetailMd.showFolderDetail(folderToShow, null);
			}else{
				activity.folderMd.showFolderList();
			}					
		}							
	}
}
